<template>
    <div class="role">
            <!-- 功能选择区 -->
            <div class="selection">
            <div @click="refresh(1)">
                <el-button type="info"><el-icon><RefreshRight /></el-icon></el-button>
            </div>
            <div @click="add()">
                <el-button type="success"><el-icon size="22" style="margin-right: 2px;"><Plus /></el-icon>添加</el-button>
            </div>
        </div>
        <!-- table -->
        <div class="table_box">
        <el-table  ref="ref_multipleTableRef" :data="tableData" height="90vh" @row-dblclick="db_Click"> <!--单击 和 双击 && 单选 和全选 -->
            <el-table-column type="selection" width="50" align="left" />
            <el-table-column label="序号" width="80" type="index" align="left"/>
            <el-table-column prop="username" label="用户名" width="150"/>
            <el-table-column prop="user" label="账号" width="150" align="left"/>
            <el-table-column prop="password" label="密码" width="150" />
            <el-table-column prop="role" label="权限" width="150" align="left" />
            <el-table-column fixed="right" label="执行操作" width="280" align="center">
                <template #default="scope">
                   <div>
                        <el-button type="danger" style="width: 150px;"  @click.prevent="del(scope.$index)">
                            <el-icon size="20"><DeleteFilled /></el-icon>删除
                        </el-button>
                   </div>
                </template>
                </el-table-column>
        </el-table>
        </div>
          <!-- form表单 -->
          <el-dialog
            v-model="dialogVisible"
            title="编辑表单"
            draggable
            width="35%">
            <el-form :model="form" class="demo-ruleForm" v-loading="loading" size="large">

            <el-form-item required label="昵称" label-width="120px">
                <el-input v-model="form.username" type="text" autocomplete="off" placeholder="请输入管理员昵称" />
            </el-form-item>

            <el-form-item required label="账号" label-width="120px">
                <el-input v-model="form.user" type="text" autocomplete="off" placeholder="请输入管理员账号" />
            </el-form-item>

            <el-form-item required label="密码" label-width="120px">
                <el-input v-model="form.password" type="text" autocomplete="off" placeholder="请输入管理员密码" />
            </el-form-item>

            <el-form-item required label="权限设置" label-width="120px">
                <div class="roles" v-for="(item,index) in qxList" :key="index" >
                    <el-checkbox v-model="qxList[index].checked">
                        <el-icon ><component :is="item.icon" /></el-icon>{{ qxList[index].name }}
                    </el-checkbox>
                </div>
            </el-form-item>
            

            </el-form>
        <template #footer>
            <span class="dialog-footer">
            <el-button type="primary" @click="submit()" style="width: 80%;margin-right: 8%;height: 40px;">
                {{ btn_text }}
            </el-button>
            </span>
        </template>
        </el-dialog>

        <messageComp ref="ref_messageComp"> </messageComp>
    </div>
  
</template>

<script setup>
import axios from "axios"
import { ref,getCurrentInstance } from "vue"
import { useStore } from "vuex";
import messageComp from "../components/messageComp.vue";
const ref_messageComp = ref(null) //弹窗message组件refs
const store = useStore()
const { ctx } = getCurrentInstance()
// 数据
let loading = ref(false) //加载
let dialogVisible = ref(false) //表单开关
let form = ref({role:''}) //表单数据 el-form
let tableData = ref([]) //表格数据-el-table
let btn_text = ref('添加')
let qxList = ref(store.state.menuList)

// 提交
const submit = ()=>{
    if (btn_text.value == '添加') {
        addAPI()
    } else {
        updateAPI()
    }
   
}

const db_Click = (e)=>{
    dialogVisible.value = true
    btn_text.value = '修改'
    form.value = e
    // 遍历权限数字
    const role = e.role.split(',')
    //去掉最后一个字符
    role.pop()
    console.log(role);
    // 循环role数组，如果role数组中包含qxList.id，则qxList.checked为true
    for (let i = 0; i < role.length; i++) {
        for (let j = 0; j < qxList.value.length; j++) {
            if (Number(role[i]) == qxList.value[j].id) {
                qxList.value[j].checked = true
            }
        }
    }

}

const updateAPI = () =>{
    form.value.type = '管理员'
    form.value.role = []
    // // 遍历权限数字
    for (let i = 0; i < qxList.value.length; i++) {
        if (qxList.value[i].checked == true) {
            form.value.role += qxList.value[i].id +','
        }
    }
    dialogVisible.value = false
    // console.log(form.value);
    axios({
        method:'post',
        url:store.state.url + '/users/update',
        data:form.value,
    }).then(res=>{
        if (res.data.code == 200) {
            ref_messageComp.value.messageSuccess('您更新了一条记录')
            refresh()
        }else{
            ref_messageComp.value.messageFail('更新失败')
        }
    }).catch(err=>{
        ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
    })
}
const addAPI = ()=>{
     // 遍历权限数字
     for (let i = 0; i < qxList.value.length; i++) {
        if (qxList.value[i].checked == true) {
            form.value.role += qxList.value[i].id +','
        }
    }
    // 改变用户类型为管理员
    form.value.type = '管理员'
    dialogVisible.value = false
    axios({
        method:'post',
        url:store.state.url + '/users/register',
        data:form.value,
    }).then(res=>{
        if (res.data.code == 200) {
            ref_messageComp.value.messageSuccess('您新增了一条记录')
            refresh()
        }else{
            ref_messageComp.value.messageFail('新增失败')
        }
    }).catch(err=>{
        ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
    })
}
// 获取用户列表
const getData = ()=>{
    axios({
        url:store.state.url + '/users'
    }).then(res=>{
        console.log(res);
        if (res.data.code == 200) {
            let arr = res.data.data
            tableData.value = [] //清空数组内容
            // tableData.value = arr
            for (const index in arr) {
                if (arr[index].type == '管理员') {
                    tableData.value.push(arr[index])
                }
            }
        }
    }).catch(err=>{
        ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
    })
}

// 删除
const del = (index)=>{
    loading.value = true
    let timer = setInterval(() => {
            axios({
            method:'post',
            url:store.state.url + '/users/delete',
            data:{
                id:tableData.value[index].id
            },
        }).then(res=>{
            if (res.data.code == 200) {
                ref_messageComp.value.messageSuccess('您删除了一条记录')
                refresh()
            }else{
                ref_messageComp.value.messageFail('删除失败！')
            }
        }).catch(err=>{
            ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
        })
        loading.value = false
        clearInterval(timer)
    }, 1000);

}
// 刷新
const refresh = (n)=>{
    tableData.value = []
    if (n) {
        ref_messageComp.value.loading({dom:'.role',text:'数据拉取中..',},1000,()=>{
            ref_messageComp.value.messageSuccess('刷新成功')
            getData()
        })
        return;
    }
    getData()
}
const add = ()=>{
    form.value = {role:''}
    dialogVisible.value = true
    btn_text.value = '添加'

}
// 执行区
refresh()
</script>


<style scoped>
.role{
    position: absolute;
    top: 0%;
    left: 0px;
    width: 100%;
    height: 100%;
    border: 2px solid #ccc;
    color: black;
    border-radius: 10px;
    /* border: 1px solid ; */
}
.selection{
    margin: 10px;
    width: 100%;
    height: 40px;
    line-height: 40px;
    /* border: 2px solid; */
    display: flex;

}
.selection>div{
    width: 70px;
    height: 100%;
    margin-left: 10px;
    border-radius: 5px;
}
/* 刷新 */
.selection>div:nth-child(1){
    margin-left: 40px;
}
.roles{
    width: 40%;
    margin: 5px;
    /* border: 2px solid ; */
}


</style>